#include <avr/io.h>
#include <avr/interrupt.h>

#define F_CPU 1000000UL

#include <util/delay.h>

#define output_low(port,pin) port &= ~(1<<pin)
#define output_high(port,pin) port |= (1<<pin)
#define set_input(portdir,pin) portdir &= ~(1<<pin)
#define set_output(portdir,pin) portdir |= (1<<pin)

ISR (PCINT_vect);

volatile int SWITCH_PRESSED = 0;
volatile int timerCounter=0;
volatile int BLINK = 0;

int BUZZER_ON = 0; //Flag to indicate that the buzzer is on
volatile int BUZZER_STATE = 0;
volatile int BUZZER_COUNTER_REF = 10;//Indicate frequency
volatile int BUZZER_COUNTER = 0;
volatile int START = 0;

int main(void)
{
	set_output(DDRD,PD5);
	set_output(DDRD,PD6);
	set_output(DDRB,PB1);
	output_high(PORTD,PD5);
	
	GIMSK = _BV (PCIE);
	PCMSK = _BV (PCINT3);
	MCUCR = _BV (ISC00);

	//Set timer 
	TCCR1B |= (1 << WGM12);
	OCR1A = F_CPU / 256;
	TCCR1B |= (1 << CS12);
	TIMSK |= (1 << OCIE1A);


	//Set timer
	TCCR0B |= (1 << WGM12);
	OCR0A = F_CPU / 1024 * 10;
	TCCR0B |= (1 << CS12);
	TIMSK |= (1 << OCIE0A);

	sei();

    while(1)
    {
		//output_high(PORTD,PD6);
		//_delay_ms(10);
		//output_low(PORTD,PD6);
		//_delay_ms(500);
        //TODO:: Please write your application code 
    }
}

ISR(TIMER1_COMPA_vect)
{
	if (START==0) return;
	if (timerCounter>0) {
		timerCounter--;
		return ;
	}
	START = 0;
	output_low(PORTD,PD6);
	output_low(PORTB,PB1);
	output_high(PORTD,PD5);
}

ISR(TIMER0_COMPA_vect)
{
	if (START==0) return;
	
	BUZZER_COUNTER=!BUZZER_COUNTER;
	if (BUZZER_COUNTER==1) {
		output_high(PORTB,PB1);
	} else {
		output_low(PORTB,PB1);
	}
}

//Start test mode when PCINT3 is pulled up
ISR (PCINT_vect)
{
	SWITCH_PRESSED=!SWITCH_PRESSED;
	if (SWITCH_PRESSED==1) {
		output_high(PORTD,PD6);
		output_low(PORTD,PD5);
		START=1;
		timerCounter=5;
	}
}